package com.snake.mylibrary.crash;


import android.content.Context;

import com.snake.mylibrary.utils.ThreadManagerUtil;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

/**
 * 捕获出现的crash,写入到文件/data/data/packageName/cache/log/下
 */
public class CrashManager implements Thread.UncaughtExceptionHandler {
    private static Context sContext;
    private CrashManager() {
        Thread.setDefaultUncaughtExceptionHandler(this);
    }

    public static void init(Context context) {
        sContext  =context;
    }

    @Override
    public void uncaughtException(Thread t, Throwable e) {
        ThreadManagerUtil.getInstance().getSingleThreadExecutor().execute(new WriteToFileTask(t, e));
    }


    class WriteToFileTask implements Runnable {
        private SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);
        private Thread mThread;
        private Throwable mThrowable;

        @Override
        public void run() {
            Writer writer = new StringWriter();
            PrintWriter printWriter = new PrintWriter(writer);
            mThrowable.printStackTrace(printWriter);
            printWriter.close();
            String result = writer.toString();
            String fileName = "crash";
            File cacheDir = sContext.getCacheDir();
            String path = cacheDir.getAbsolutePath();
            File logDir = new File(path, "log");
            if (!logDir.exists()) {
                logDir.mkdirs();
            }
            File logFile = new File(logDir, fileName);
            writeStringToFile(logFile, result);

        }

        public WriteToFileTask(Thread t, Throwable e) {
            this.mThread = t;
            this.mThrowable = e;
        }


        public void writeStringToFile(File file, String s) {
            try {
                FileWriter fw = new FileWriter(file,true);
                BufferedWriter bw = new BufferedWriter(fw);
                String time = formatter.format(new Date());
                bw.write(time);
                bw.newLine();
                bw.write(mThread.getName());
                bw.newLine();
                bw.write(s);
                bw.close();
                fw.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


}
